<?php
/**
 * OJBETO DB
 * 
 * Provee de una funcion para ejecutar las cosultas
 * 
 * @author Jose Flores <josefloressv@gmail.com>
 * @copyright (c) 2012, InterMall
 * 
*/
final class DB{

	private static $instance;	
	public static $db=NULL;
	private static $server;
	private static $username;
	private static $password;
	private static $databasename;
	private static $last_id;

    private function __construct(){}
	private function __clone(){}

    /**
     * INIT
     * Constructor Manual de la Clase
    */    	
	static final function init(){
		self::$server="mysql.wbtstng.info";
		self::$username="usrcanela";
		self::$password="3jkhn0BOZz";
		self::$databasename='clavoycanela_db';
		try {
			self::$db=new mysqli(self::$server, self::$username, self::$password, self::$databasename);
			if (self::$db->connect_errno) {
				Log::write("ERROR AL CONECTAR", self::$db->connect_error);
			}
		} catch (Exception $e) {
			Log::write("ERROR AL INICIAR DB", $e->getMessage());
		}		
	}

    /**
     * UNA SOLA INSTANCIA 
    */
    public static function getInstance()
    {
      if (  !self::$instancia instanceof self)
      {
         self::$instancia = new self;
      }
      return self::$instancia;
    }
	
	/**
	 * EJECUTAR QUERY
	 * 
	 * Ejecuta una consulta pasado como parametro y retorna un Resulset
	 * @param string SQL que se quiere ejecutar
	 * @return resultset Resultado de la Query 
	*/
	static final function query($sql){
		try{
			if(self::$db){
				if(!empty($sql)){
					//Log::write("SQL",$sql);	
					$rs=self::$db->query($sql);
					if (self::$db->error) {
						Log::write("ERROR EN QUERY","sql: ".$sql."\nmsg: ".self::$db->error);
					}
					return $rs;
				}else{
					Log::write("ERROR SQL","Consulta Vacia");	
				}
			}else{
				Log::write("ERROR DB","Objeto db No inicializado\nQuery:".$sql);
			}
		}catch(Exception $ex){
			Log::write("ERROR EN QUERY",$sql);
			throw $ex;
		}
		return NULL;
	}
	static final function lastID(){		
		return self::$db->insert_id;
	}
	static final function affected_rows(){		
		return self::$db->affected_rows;
	}
	static final function num_rows(){		
		return self::$db->num_rows;
	}	
	// Agregar un metodo para cerrar conexiones, luego de finalizar script
	//mysqli_free_result($rs)
}
?>